//
//  SearchViewController.m
//  XhlTrip
//
//  Created by dllo on 15/8/31.
//  Copyright (c) 2015年 蓝鸥科技. All rights reserved.
//

#import "SearchViewController.h"
#import "MJTableView.h"
#import "MJRefresh.h"
#import "TravelViewCell.h"
#import "LeaonWorking.h"
#import "TravelDetailController.h"
#import "UIImageView+WebCache.h"
#import "TravelModel.h"
#import "MBProgressHUD.h"


NSInteger q = 2;
@interface SearchViewController ()<UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate, MJTableViewDelegate>

@property (nonatomic, retain) MJTableView *tableView;
@property (nonatomic, retain) NSMutableArray *travelArr;
@property (nonatomic, retain) NSString *searchbarString;
@property (nonatomic,retain) UISearchBar *searchBar;


@end

@implementation SearchViewController
- (void)dealloc
{
    [_travelArr release];
    [_searchBar release];
    [_searchbarString release];
    [_tableView release];
    [super dealloc];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 45 * Height)];
    self.searchBar.placeholder = @"请输入数字~地点或者国家进行搜索";//设置占位符
   
    self.searchBar.translucent = YES;
   
    _searchBar.delegate = self;
    self.searchBar.autocapitalizationType = UITextAutocorrectionTypeDefault;
    
    //设置控件代理
    [self.view addSubview:self.searchBar];
    [_searchBar release];

    self.view.backgroundColor = [UIColor whiteColor];
       
    /* 调用tableview */
    [self createTableView];
}


- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
   
    if (_searchBar.text.length == 0) {
        
        
            }else{
                
    }
}

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    searchBar.showsCancelButton = YES;
   
    for(id cc in [searchBar subviews])
    {
        if([cc isKindOfClass:[UIButton class]])
        {
            UIButton *btn = (UIButton *)cc;
            [btn setTitle:@"取消"  forState:UIControlStateNormal];
        }
    }
   
    return YES;
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    searchBar.text = @"";

}

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {
   
    searchBar.showsCancelButton = NO;
    
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [_searchBar resignFirstResponder];
       self.searchbarString = [searchBar.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [self.travelArr removeAllObjects];
    [self handdata];
 

    NSLog(@"search clicked");
}

//点击搜索框上的 取消按钮时 调用
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    NSLog(@"cancle clicked");
    _searchBar.text = @"";
    [_searchBar resignFirstResponder];
    
}
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
       
        self.travelArr = [NSMutableArray array];
        
    }
    return self;
}





#pragma mark - 网络请求
- (void)handdata
{
   
    MBProgressHUD *hud = [[MBProgressHUD alloc] initWithView:self.view];
   
    hud.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:hud];
    hud.labelText = @"正在加载";
    [hud show:YES];
        /* 下面的tableview的网络请求 */
    NSString *dd = [NSString stringWithFormat:@"%@%@%@", @"https://chanyouji.com/api/search/trips.json?q=", self.searchbarString, @"&page=1"];
    NSString *nn = [NSString stringWithFormat:@"%@%@", @"search", self.searchbarString];
    [LeaonWorking netWorkingHanderGetGataWithUrl:dd pathname:nn resultBlock:^(id result) {
        
        [self.travelArr addObjectsFromArray:result];
        
        /* tableview 重新加载数据 */

        [_tableView reloadData];
        [hud removeFromSuperview];
        [hud release];
    }];
    
}


#pragma mark - 创建tableview
- (void)createTableView
{
    self.tableView = [[MJTableView alloc] initWithFrame:CGRectMake(0, 40 * Height, self.view.frame.size.width, self.view.frame.size.height - 50 * Height) style:UITableViewStylePlain delegate:self];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.rowHeight = 210 * Height;
      [self.view addSubview:_tableView];
    [_tableView release];
}





- (void)refreshingHeader:(id)tableView {
    NSLog(@"下拉刷新");
    
    /* 下面的tableview的网络请求 */
     NSString *dd = [NSString stringWithFormat:@"%@%@%@", @"https://chanyouji.com/api/search/trips.json?q=", self.searchbarString, @"&page=1"];
    [LeaonWorking netWorkingHanderGetGataWithUrl:dd pathname:@"search" resultBlock:^(id result) {
        [self.travelArr removeAllObjects];
        [self.travelArr addObjectsFromArray:result];
        
        /* tableview 重新加载数据 */
        [_tableView reloadData];
    }];
    
}

- (void)refreshingFooter:(id)tableView {
    NSLog(@"上啦加载");
    
    NSString *page = [NSString stringWithFormat:@"%ld", (long)q];
     NSString *dd = [NSString stringWithFormat:@"%@%@%@%@", @"https://chanyouji.com/api/search/trips.json?q=", self.searchbarString, @"&page=", page];
   
    
    NSString *ss = [NSString stringWithFormat:@"%@%@", @"search", page];
    [LeaonWorking netWorkingHanderGetGataWithUrl:dd pathname:ss resultBlock:^(id result) {
        [self.travelArr addObjectsFromArray:result];
        
        /* tableview 重新加载数据 */
        [_tableView reloadData];
    }];
    
    q = q + 1;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *reuse = @"rr";
    TravelViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
    if (cell == nil) {
        cell = [[[TravelViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuse] autorelease];
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell.SmallImageView sd_setImageWithURL:[[self.travelArr[indexPath.row] objectForKey:@"user"] objectForKey:@"image"]];
    
    

    
    TravelModel *model = [[TravelModel alloc] init];
    [model setValuesForKeysWithDictionary:self.travelArr[indexPath.row]];
    cell.travelModel = model;
    [model release];
    
    if ([cell.nameLabel.text rangeOfString:self.searchBar.text].location != NSNotFound) {
        cell.nameLabel.attributedText =[self changeWithString:cell.nameLabel.text light:self.searchBar.text];
    }
    return cell;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.travelArr.count;
}


#pragma mark - 点击cell进入详情
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    TravelDetailController *travelDetail = [[TravelDetailController alloc] init];
    [travelDetail passDetailValue:[NSString stringWithFormat:@"%@", [self.travelArr[indexPath.row] objectForKey:@"id"]]];
    [self.navigationController pushViewController:travelDetail animated:YES];
    [travelDetail release];
}


- (NSMutableAttributedString *)changeWithString:(NSString *)string light:(NSString *)light
{
    NSMutableAttributedString *attributeString = [[[NSMutableAttributedString alloc]initWithString:string] autorelease];
    for (int i = 0; i < attributeString.length - light.length + 1; i ++) {
        if ([[string substringWithRange:NSMakeRange(i, light.length)]isEqualToString:light]) {
            // 设置高亮
            NSRange range = NSMakeRange(i, light.length);
            [attributeString addAttribute:NSForegroundColorAttributeName value:[UIColor yellowColor] range:range];
            [attributeString addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Verdana-BoldItalic" size:20 * Width] range:range];
            
        }
    }
    return attributeString;
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
        
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
